package org.ddd.specification.selection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.ddd.specification.Specification;

public class Selector<T> {
    private final List<T> contentList;

    private Selector(Collection<T> content) {
        this.contentList = new LinkedList<T>(content);
    }

    public List<T> all() {
        return new ArrayList<T>(contentList);
    }

    public List<T> where(Specification<? super T> specification) {
        List<T> matches = new ArrayList<T>();
        for (T candidate : contentList) {
            if (specification.isSatisfiedBy(candidate)) {
                matches.add(candidate);
            }
        }
        return matches;
    }

    public static <X> Selector<X> from(Collection<X> content) {
        return new Selector<X>(content);
    }

    public static <X> Selector<X> fromElements(X... elements) {
        return from(Arrays.asList(elements));
    }

    public Selector<T> only(Specification<? super T> specification) {
        return from(this.where(specification));
    }

}
